<?php
/**
 * Created by PhpStorm.
 * User: 李闯
 * Date: 2020/7/21
 * Time: 15:43
 * Content: 商品管理
 */

namespace app\admin\controller;
use app\reuse\controller\ResponseJson;
use app\service\BizproService;
use app\service\CategoryService;
use app\service\ResourceService;
use phpmailer\BaseException;
use Redis\Redis;
use think\Db;
use think\facade\Session;

class Bizpro extends Common
{
    use ResponseJson;

    function __construct()
    {
        parent::__construct();
    }
    /*
     * @param null
     * @content 商品列表
     * @return array
     * */
    function index()
    {
//        $re=Db::name('member_orderdetail')->field('bizpro_id,price,buy_num')->select();
//        foreach ($re as $v) {
//            Db::name('bizpro')->where('id=' . $v['bizpro_id'])->setInc('total_sale', $v['price']*$v['buy_num']);
//        }
//
        if(input("get.active") == "ajax"){
            # 搜索条件
            $searchParams = input('post.searchParams');
            $_where = "b.status != 3";
            if (!empty($searchParams)) {
                # 商品名称 货号搜索
                if (!empty($searchParams['search'])) {
                    $_where .= " and b.name like '%" . $searchParams['search'] . "%'
                     or b.bizpro_number like '%" . $searchParams['search'] . "%' 
                   ";
                }
                # 状态筛选
                if (!empty($searchParams['status'])) {
                    $_where .= " and b.status = " . $searchParams['status'];
                }

                # 供应商筛选
                if (!empty($searchParams['supplier_id'])) {
                    $_where .= " and b.supplier_id = " . $searchParams['supplier_id'];
                }
                # 商品分类筛选
                if (!empty($searchParams['class_id'])) {
                    $_where .= " and b.class_id = " . $searchParams['class_id'];
                }

            }

            # 定义listRows 分页
            $listRows = input('post.limit');
            if (empty($listRows)) {
                $listRows = 10;
            }
            $info = Db::table('bizpro b')
                //"b.*,bc.title,s.supplier_name,(b.real_num+b.fake_num) total_num"
                ->field("b.*,bc.title,s.supplier_name,b.real_num total_num")
                ->leftJoin("bizpro_class bc","bc.id = b.class_pid")
                ->leftJoin("supplier s","s.id = b.supplier_id")
                ->order("b.create_time desc")
                ->where($_where)
                ->paginate($listRows, false, ['query' => request()->param()]);

            $info=$info->toArray();
            foreach ($info['data'] as &$v)
            {
                $name='';
              $v['standard_base'] =json_decode($v['standard_base'],true);
               // $v['total_sale'] = number_format($v['total_sale'],2);
              foreach ($v['standard_base'] as $vv)
              {
                  $name.=$vv['name'].',';
                  $name=substr($name,0,strrpos($name,','));
              }
              $v['standard_base'] = $name;
              $v['standard_desc']=Db::name('standard_detail')->where('bizpro_id='.$v['id'])->value('standard_desc');
              $v['standard_desc']=json_decode( $v['standard_desc'],true);
              $arr=arraySort($v['standard_desc'],'sale_price','asc');
              $v['sale_price'] = number_format($arr[0]['sale_price'],2);


            }

            return $this->jsonSuccessData($info);
        }else{
            #获取供应商信息
            $supplier = Db::table("supplier")->field("id,supplier_name")->select();
            #获取商品分类信息
            $bizpro_class = Db::table("bizpro_class")->field("id,title,pid")->select();
            #查询下级 递归 无限极分类
            $class = getTree($bizpro_class);

            $this->assign('supplier',$supplier);
            $this->assign('bizpro_class',$class);
            return $this->fetch();

        }

    }
    /*
      * @param null
      * @content 商品创建编辑
      * @return array
      * */
    public function Saveinfo()
    {
        if(input("get.active") == "ajax"){
            // 是否ajax

            // 开始操作 接收参数
            $params = $this->data_post;
//            ($params);die;

            //整理数据 删除多与图片字段
            $data=BizproService::HandleData($params);
           // ($data);exit;
            BizproService::SaveCate($data,$params);
            return DataReturn('保存成功', 0);
        }else{
            #删除规格缓存
            Session::delete('bizproStandard');
            #根据 商品id 判断是创建  还是修改
            // 参数
            $params = input();
            $biz_params=[];
            if(!empty($params['id'])){
                Session("source_upload",null);
                #查询商品信息
                $info = Db::table("bizpro")->where("id = '".$params['id']."'")->find();
                $info['supplier_title']=Db::name('supplier')->where('id='.$info['supplier_id'])->value('supplier_name');
                if(!empty($info['imgurl'])){
                    ResourceService::setUploadCache($info['imgurl'],'img');
                }
//                $_detail_img=get_images_from_html($info['detail']);
//                if(!empty($_detail_img)){
//                    foreach($_detail_img as $k=>$v){
//                        ResourceService::setUploadCache(wipeOffFormStr($v),'img');
//                    }
//                    $info['detail']=join(',',$_detail_img);
//
//                }
                $_bannerurl=explode(",",$info["banner"]);
                $this->assign("bannerArr",$_bannerurl);

                if(!empty($_bannerurl)){
                    foreach($_bannerurl as $k=>$v){
                        ResourceService::setUploadCache($v,'img');
                    }
                }

                $standard_base=json_decode($info['standard_base'],true);
                for($i=1;$i<2;$i++){
                    $standard_base[$i]['name']=isset($standard_base[$i]['name'])?$standard_base[$i]['name']:'';
                    $standard_base[$i]['value']=isset($standard_base[$i]['value'])?$standard_base[$i]['value']:[];
                }

                $this->assign('standard_base',$standard_base);
                #查询规格
                $standard = Db::table("standard_detail")->where("bizpro_id = '".$params['id']."'")->value('standard_desc');
                # 查询参数
                $biz_params=json_decode($info['params'],true);
                #用来删除图片的 是个数组
                $info["bannerurl"]=implode(',',array_map("change_to_quotes",$_bannerurl));
                $this->assign('standard_price_arr',json_decode($standard,true));
                $this->assign('bizpro',$info);
                $this->assign('bannerurl',$info["bannerurl"]);
                $this->assign('id',$params['id']);
            }
            $this->assign('bizpro_params',$biz_params);
            #查询商品分类
            $class = Db::table("bizpro_class")->where('pid = 0')->field("id,title")->select();
            $seclass = Db::table("bizpro_class")->where('pid > 0')->field("id,title")->select();
//            ($info);exit;
            #查询商品专区
            $spearea= Db::table("bizpro_spearea")->field("id,title")->select();
            #查询商品供应商
            $supplier = Db::table("supplier")->field("id,supplier_name")->select();
            $this->assign('class',$class);
            $this->assign('seclass',$seclass);
            $this->assign('spearea',$spearea);
            $this->assign('supplier',$supplier);
            return $this->fetch();
        }
    }
    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context 商品删除
     */
    function bizpro_del()
    {
        $id=input("post.id");
        Db::table("bizpro")->where(array("id"=>$id))->update(array("status"=>3));
        return array("status"=>true);
    }
    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context 创建商品规格
     */
    function standard(){
//        Session::delete('bizproStandard');die;
        $_info = input("post.");
        $value = input("post.title");
        $mark = input("post.mark");
        #判断是否有商品id
        $proId = input("post.proId");
        if($mark == 'DB'){
            #查询
            $standard = Db::table("standard_detail")->where("bizpro_id = $proId")->select();
            $str = $this->getSessionDb($standard,'DB');
        }else{
            if(empty($value)){
                #修改
                $standard = Session::get('bizproStandard');
                $str = $this->getSessionDb($standard,'S');
            }else{
                #添加
                #获取缓存
                $bizpro_standard = Session::get('bizproStandard');
                if(empty($bizpro_standard)){
                    #存
                    Session::set('bizproStandard',array($_info));
                }else{
                    #放在一个二维数组里
                    array_push($bizpro_standard,$_info);
                    Session::set('bizproStandard',$bizpro_standard);
                }
                #获取缓存
                $standard = Session::get('bizproStandard');
                $str = $this->getSessionDb($standard,'S');
            }
        }
        return array('status'=>true,'str'=>$str);

    }
    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context 商品规格展示
     */
    function getSessionDb($array,$mark)
    {
        if (!empty($array and is_array($array))) {
            #遍历数据
            $str_body = null;
            $str = null;
            foreach ($array as $k => $v) {
                $str_body .= "
                        <div   style='float: left;width:100px;height:50px; background: aliceblue;' 
                        onclick=\"bizStandardDel('" . $mark . "','" . $v['title'] . "','" . $k . "')\"><button>{$v['title']}</button></div>
                        
                      ";

            }
            $str .= $str_body;

            return $str;
        }
    }
    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context 修改缓存中的商品规格和数据库的
     */
/*    function bizStandardWrite(){
        $value = input("post.value");
        $mark = input("post.mark");
        #缓存  则是 建值   Db  则是 id
        $id = input("post.id");

        if($mark == "S"){
            #修改缓存中
            # 获取session中的数组信息
            $session_standard = Session::get('bizproStandard');

            $session_standard[$id] = $value;
            # 修改完成,重新存入session
            Session::set('bizproStandard', $session_standard);

            return array("status"=>true);


        }else if($mark == "DB") {
            #修改数据库

        }


    }*/
    /**
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     * @context 删除缓存中的商品规格和数据库的
     */
    function bizStandardDel(){

        $mark = input("post.mark");
        #缓存  则是 建值   Db  则是 id
        $id = input("post.id");

        if($mark == "S"){
            #修改缓存中
            # 获取session中的数组信息
            $session_standard = Session::get('bizproStandard');
            unset($session_standard[$id]);

            # 修改完成,重新存入session
            Session::set('bizproStandard', $session_standard);
            $standard = Session::get('bizproStandard');

            return array("status"=>true);

        }else if($mark == "DB") {
            #修改数据库
            Db::table("standard_detail")->where("id = $id")->delete();
            return array("status"=>true);
        }

    }


    /**
     * 执行编辑/添加参数.
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年6月23日09:57:30
     */
    public function DoSaveParam()
    {
        // 是否ajax
        if (!IS_AJAX) {
            return $this->error('非法访问');
        }

        // 开始操作
        $params = $this->data_post;

       // 公共数据校验请求参数
        $p = [
            [
                'checked_type' => 'empty',
                'key_name' => 'title',
                'error_msg' => '名称不能为空',
                'error_code' => 30003,
            ],
            [
                'checked_type' => 'empty',
                'key_name' => 'params',
                'error_msg' => '答案不能为空',
                'error_code' => 30004,
            ],
        ];

        $ret=ParamsChecked($params, $p);

        if(true !== $ret)
        {
            //$error_arr[0]  $error_arr[1]
            $error_arr = explode(',', $ret);
            throw new BaseException(['code'=>403 ,'errorCode'=>$error_arr[1],'msg'=>$error_arr[0],'status'=>false,'debug'=>false ]);
        }



        //名称重复判断
        $check_data = [
            'where' => [['title', '=', $params['title']],['bizpro_id', '=', $params['bizpro_id']]],
            'table' => 'bizpro_params',
            'params' => $params,
            'msg' => '名称不能重复',
            'error_code' => 20005,
        ];
        CategoryService::CheckTitle($check_data);



        if(!$re)
        {
            throw new BaseException(['code' => 403, 'errorCode' => '30007', 'msg' => '保存参数失败', 'status' => false, 'debug' => false]);
        }
        return json(['status'=>true,'data'=>$params]);
    }

    /**
     * 查找二级分类.
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年6月23日09:57:30
     */
    public function bizclass()
    {
        $params = $this->data_get;
        $data_params = [
            'where' => ['pid'=>$params['pid']],
            'field' => 'id,title',
            'table'=>'bizpro_class'
        ];
        $ret =  CategoryService::DataList($data_params);
        $re = CategoryService::GoodsCategoryDataDealWith($ret);

        return json(['status'=>true,'data'=>$re]);
    }

    /**
     * 批量上下架.
     * @author   juzi
     * @blog    https://blog.csdn.net/juziaixiao
     * @version 1.0.0
     * @date    2020年6月23日09:57:30
     */
    public function  BatchShell()
    {
        $params = $this->data_post;
        $id=explode(',',$params['id']);
        array_pop($id);

        Db::name('bizpro')->where([['id','in',$id]])->update(['status'=>$params['action']]);
        return json(DataReturn('保存成功',0));
    }



}